package top.jacktgq.hsp.nio.buffer_channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @Author CandyWall
 * @Date 2020/11/11--14:08
 * @Description Scattering：将数据写入到Buffer时，可以采用Buffer数组依次写入
 *              Gathering：从Buffer读取数据时，可以采用Buffer数组依次读
 */
public class ScatteringAndGathering {
    public static void main(String[] args) throws Exception {
        //使用ServerSocketChannel和SocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口到Socket，并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建一个Buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待客户端连接（telnet)，只能连接一个
        SocketChannel socketChannel = serverSocketChannel.accept();
        int  messageLength = 8; //假定从客户端接收8个字节，如果发送的内容超过8个，下一次循环再继续获取
        //循环读取
        while (true) {
            int byteRead = 0;
            //直到读取到8个字符才能退出本循环
            while (byteRead < messageLength) {
                long len = socketChannel.read(byteBuffers);
                byteRead += len; //累计读取的字节数
                System.out.println("byteRead = " + byteRead);
                //使用流打印当前的这个buffer的position和limit
                Arrays.asList(byteBuffers).stream().map(buffer -> "position = " +
                        buffer.position() + ", limit = " + buffer.limit()).forEach(System.out::println);
            }

            System.out.println("-------------------------");

            //将所有的buffer进行flip
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());
            //将数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long len = socketChannel.write(byteBuffers);
                byteWrite += len;
            }
            //将所有的buffer进行clear
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());
            System.out.println("byteRead = " + byteRead + ", byteWrite = " + byteWrite + ", messageLength = " + messageLength);
        }
    }
}
